package org.apache.commons.digester.xmlrules;

import org.apache.commons.digester.AbstractObjectCreationFactory;
import org.apache.commons.digester.Digester;
import org.apache.commons.digester.PropertyParamRule;
import org.apache.commons.digester.Rule;
import org.xml.sax.Attributes;

/**
 * andrew 31.01.2006 0:33:33
 */
public class JimexDigesterRuleParser extends DigesterRuleParser {

    public void addRuleInstances(Digester digester) {
        super.addRuleInstances(digester);
        digester.addFactoryCreate("*/property-param-rule", new PropertyParamRuleFactory());
        digester.addRule("*/property-param-rule", new PatternRule("pattern"));
        digester.addSetNext("*/property-param-rule", "add", Rule.class.getName());
    }

    protected class PatternRule extends Rule {

        private String attrName;
        private String pattern = null;

        /**
         * @param attrName The name of the attribute containing the pattern
         */
        public PatternRule(String attrName) {
            super();
            this.attrName = attrName;
        }

        /**
         * If a pattern is defined for the attribute, push it onto the
         * pattern stack.
         */
        public void begin(Attributes attributes) {
            pattern = attributes.getValue(attrName);
            if (pattern != null) {
                patternStack.push(pattern);
            }
        }

        /**
         * If there was a pattern for this element, pop it off the pattern
         * stack.
         */
        public void end() {
            if (pattern != null) {
                patternStack.pop();
            }
        }
    }

    private static class PropertyParamRuleFactory extends AbstractObjectCreationFactory {
        public Object createObject(Attributes attributes) throws Exception {
            int paramIndex = Integer.parseInt(attributes.getValue("paramnumber"));
            String keyName = attributes.getValue("value");
            final Rule paramRule = new PropertyParamRule(paramIndex, keyName);
            return paramRule;
        }

    }
}
